import { isEmpty } from "lodash";

function getClassPropsByAst (ast: any) {
  const classAst = findClassAst(ast);
  if (classAst) {
    return classAst.body.body
      .filter((item: any) => item.type === 'ClassProperty')
      .map((item: any) => ({
        name: item.key.name
      }));
  }

}

function getClassEventsByAst (ast: any) {
  if (!ast || isEmpty(ast)) return [];
  const classAst = findClassAst(ast);
  if (classAst) {
    return classAst.body.body
      .filter((item: any) => item.type === 'ClassMethod')
      .map((item: any) => ({
        name: item.key.name
      }));
  }

}

function findClassAst (ast: any): any {
  switch (ast.type) {
    case 'ClassDeclaration':
      return ast;
    case 'File':
      return findClassAst(ast.program);
    case 'ExportDefaultDeclaration': // export 语句
      return findClassAst(ast.declaration);
    default:
      if (ast?.body?.length > 0) {
        const asts = ast.body.map((item: any) => findClassAst(item));
        try {
          const classAst = asts.find((item: any) => item && item.type === 'ClassDeclaration')
          if (classAst) return classAst;
        } catch (err) {
          return null;
        }
      }
  }
  return null;
}

export default {
  getClassPropsByAst,
  getClassEventsByAst,
  findClassAst
}